//
//  WBRefreshControl.swift
//  sinaWeibo
//
//  Created by 吴熠 on 16/11/19.
//  Copyright © 2016年 吴熠. All rights reserved.
//

/*
 根据kvo观察属性变化
 */

import UIKit

//枚举列出几种状态
enum RefreshStatue : Int {
    case Normal = 0
    case Already
    case Refreshing

}

private let refreshHeight : CGFloat = 60
class WBRefreshControl: UIControl {

    var statue : RefreshStatue = .Normal{
        didSet{
            switch statue {
            case .Normal:
                //根据状态更改UI
//                print("正常状态")
                tipLabel.text = "下拉起飞"
                indicatorView.stopAnimating()
                arrowIcon.isHidden = false
                UIView.animate(withDuration: 0.25, animations: {
                    self.arrowIcon.transform = CGAffineTransform.identity
                })
                
                if oldValue == .Refreshing{
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.scrollView!.contentInset.top = self.scrollView!.contentInset.top-refreshHeight
                    })
                    //加了要减
                }
                
            case .Already:
//                print("准备状态")
                tipLabel.text = "松开刷新"
                 UIView.animate(withDuration: 0.25, animations: {
                    self.arrowIcon.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                 })
            case .Refreshing:
//                print("正在刷新")
                tipLabel.text = "正在刷新"
                indicatorView.startAnimating()
                arrowIcon.isHidden = true
                sendActions(for: .valueChanged)
                //刷新悬停效果
                UIView.animate(withDuration: 0.25, animations: { 
                    self.scrollView!.contentInset.top = self.scrollView!.contentInset.top + refreshHeight
                })
            }
        }
    }
    
    //刷新接收的动画
    func endRefreshing(){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.statue = .Normal
        }
    }

    

    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHeight, width: kScreenW, height: refreshHeight)
        super.init(frame: rect)
//        self.backgroundColor = UIColor.gray
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //kvo设置时机,当控件被添加到父视图上的时候开始设置kvo观察
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if let fatherView = newSuperview as? UIScrollView{
            self.scrollView = fatherView
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
    }
    //观察的监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let offsetY = self.scrollView?.contentOffset.y ?? 0
        let targetOffsetY = -(self.scrollView!.contentInset.top + refreshHeight)
        
        //正在拖拽的状态
        if scrollView!.isDragging{
            //拉到很下面的时候就处于准备刷新的状态了
            if  offsetY<targetOffsetY && statue == .Normal {
                statue = .Already
            }else if offsetY>targetOffsetY && statue == .Already{
                statue = .Normal
            }
        }else{
            //停止拖拽tableView 并且当前状态是准备好刷新的状态
            if statue == .Already{
                statue = .Refreshing
            }
            
        
        }
        
    }
    
    
    
    
    private func setupUI() {
        //添加控件
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicatorView)
        //约束
        tipLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        arrowIcon.snp.makeConstraints { (make) in
            make.right.equalTo(tipLabel.snp.left)
            make.centerY.equalTo(tipLabel)
        }
        indicatorView.snp.makeConstraints { (make) in
            make.center.equalTo(arrowIcon)
        }
        
    }
    //懒加载控件
    var scrollView : UIScrollView?
    lazy var tipLabel : UILabel = UILabel(title: "下拉起飞", fontSize: 14, textColor: UIColor.orange)
    lazy var arrowIcon : UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    lazy var indicatorView : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white)
    
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}
